﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using PgBirdie.Core.Config;
using PgBirdie.Core.Model;

namespace PgBirdie.Core.Extensions
{
    public static class Extensions
    {
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
        {
            return collection == null || !collection.Any();
        }

        public static bool IsNotNullOrEmpty<T>(this IEnumerable<T> collection)
        {
            return collection != null && collection.Any();
        }

        public static int ToNumeric(this ExitCodeType value)
        {
            return (int)value;
        }

        public static Int64 ToLong(this String text)
        {
            Int64 value;
            Int64.TryParse(text, out value);
            return value;
        }

        public static IEnumerable<XElement> ToIEnumberable(this XElement element)
        {
            return (element == null || element.Value == null || element.Descendants() == null) ? new List<XElement>() : element.Descendants();
        }

        public static string AsString(this XElement element)
        {
            return (element == null || element.Value == null) ? null : element.Value;
        }

        public static string AsString(this XAttribute attribute)
        {
            return (attribute == null || attribute.Value == null) ? null : attribute.Value;
        }

        public static bool ToBool(this XAttribute attribute)
        {
            return (attribute == null || attribute.Value == null) ? false : Convert.ToBoolean(attribute.Value);
        }

        public static List<string> SplitBySpaceAndClean(this String text)
        {
            var segments = new List<string>();
            foreach (var segment in text.Split(Settings.SplitterFor.Space, StringSplitOptions.RemoveEmptyEntries))
                segments.Add(segment.Trim());
            return segments;
        }

        public static List<string> SplitByPeriod(this String text)
        {
            var segments = new List<string>();
            foreach (var segment in text.Split(Settings.SplitterFor.Period, StringSplitOptions.RemoveEmptyEntries))
                segments.Add(segment.Trim());
            return segments;
        }

        public static List<string> SplitBy(this String text, params string[] delimiters)
        {
            var segments = new List<string>();
            foreach (var segment in text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
                segments.Add(segment.Trim());
            return segments;
        }
    }
}